package com.tao.utils;

import com.tao.entity.LoginUser;
import com.tao.enums.AppHttpCodeEnum;
import com.tao.exception.SystemException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;

/**
 * @author
 * @date 2023/5/3 18:38
 * 功能：
 */
public class SecurityUtils {
    public static Authentication getAuthentication(){
        SecurityContext context = SecurityContextHolder.getContext();
        return SecurityContextHolder.getContext().getAuthentication();
    }
    public static LoginUser getLoginUser(){
        return (LoginUser) getAuthentication().getPrincipal();
    }
    public static Long getUserId() {
        try {
            return getLoginUser().getCacheUser().getId();
        } catch (Exception e) {
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }
    }
    public static List<String> getPerms(){
        try {
            return getLoginUser().getPermissions();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }
    }
    public static List<String> getRoles(){
        try {
            return getLoginUser().getRoles();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }
    }
    public static boolean isAdmin(){
        return getRoles().contains("admin");
    }

}
